import apiSendMobileCode from '../../yali-sdk/business/live/api/apiSendMobileCode';
import apiGetWxOpenId from '../../yali-sdk/business/live/api/apiGetWxOpenId';
import apiSaveAnchor from '../../yali-sdk/business/live/api/apiSaveAnchor';
import apiBandMobileCode from '../../yali-sdk/business/live/api/apiBandMobileCode';
import apiBandMobileRegister from '../../yali-sdk/business/live/api/apiBandMobileRegister';
import { SUCCESS } from '../../yali-sdk/utils/success';
import { FAIL } from '../../yali-sdk/utils/fail';
import { getExtConfig } from '../../utils/checkAuth';
import getIn from '../../yali-sdk/utils/getIn';

let timer = '';
Page({
    data: {
        num: 0,
        is_send_code: false,
        is_auth: false,
        count_down: 0,
        submit: {},
        uid: 0,
    },
    onLoad(options) {
        const self = this;
        const code = self.randomNumber();
        if (code && code !== undefined) {
            wx.setStorage({ key: 'code', data: code });
        }
        self.setData({ code, uid: options.uid ? options.uid : '' });
    },
    onUnload() {
        const self = this;
        wx.setStorage({ key: 'code', data: '' });
    },
    changeCode() {
        const self = this;
        self.setData({ code: self.randomNumber() });
    },
    randomNumber() {
        const is_change_code = Math.random().toString(8).substr(3, 4);
        return is_change_code;
    },
    bandMobile(e) {
        const phone = e.detail.value;
        phone ? this.setData({ 'submit.phone': e.detail.value, is_send_code: true }) : this.setData({ 'submit.phone': '', is_send_code: false });
    },
    bandName(e) {
        const name = e.detail.value;
        const self = this;
        self.setData({
            'submit.name': name,
        });
    },
    radioSex(e) {
        const self = this;
        const sex = !e.detail.value ? 0 : e.detail.value;
        self.setData({
            'submit.sex': sex,
        });
    },
    bandCode(e) {
        const code = e.detail.value;
        const self = this;
        const phone = self.data.submit.phone;
        if (phone) {
            code && code.length == 4 ? self.setData({ 'submit.code': code, is_send_code: true }) : self.setData({ 'submit.code': '', is_send_code: false });
        }
    },
    bandMobileCode(e) {
        const self = this;
        self.setData({
            'submit.mobile_code': e.detail.value,
            is_auth: true,
        });
    },
    sendMobileCode(e) {
        try {
            const self = this;
            // const code = wx.getStorageSync('code');
            // if (code) {
            //     const input_code = self.data.submit.code;
            //     if (code !== input_code) { // 检测动态验证码是否正确
            //         wx.showModal({
            //             content: '动态验证码错误' });
            //         return;
            //     }
            wx.showLoading();
            if (!(/^1[34578]\d{9}$/.test(self.data.submit.phone))) {
                wx.hideLoading();
                wx.showModal({
                    content: '手机号码格式错误' });
                return;
            }
            global.actionDispatcher.execute(apiSendMobileCode, {
                mobile: self.data.submit.phone,
            }, (f, fs) => {
                if (f === SUCCESS) {
                    const _this = this;
                    if (_this.data.count_down < 1) {
                        clearInterval(timer);
                        _this.data.count_down = 91;
                        timer = setInterval(() => {
                            const now_count = _this.data.count_down - 1;
                            if (now_count != -1) {
                                _this.setData({ count_down: now_count });
                            } else {
                                clearInterval(timer);
                            }
                        }, 1000);
                    }
                    wx.hideLoading();
                    wx.showToast({
                        title: '验证码发送成功',
                        icon: 'none',
                        duration: 1500,
                    });
                } else if (f === FAIL) {
                    wx.hideLoading();
                    wx.showToast({
                        title: '验证码发送失败',
                        icon: 'none',
                        duration: 1500,
                    });
                    return false;
                }
            });
            // }
        } catch (e) {
            wx.hideLoading();
            wx.showToast({ title: '验证CODE异常', icon: 'none', duration: 1500 });
        }
    },
    is_token(e) {
        wx.showLoading();
        const self = this;
        let name = self.data.submit.name;
        const sex = !e.detail.value ? 0 : e.detail.value;
        if (name) {
            name = name.replace(/[\r\n]/g, '');
            name = name.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '');
            if (name.length > 11) {
                wx.hideLoading();
                wx.showModal({ content: '主播名称长度不能超过11位' });
                return;
            }
        } else {
            wx.hideLoading();
            wx.showModal({ content: '请填写主播名称' });
            return;
        }
        if (!self.data.submit.phone) {
            wx.hideLoading();
            wx.showModal({ content: '请填写手机号码' });
            return;
        }
        // if (!self.data.submit.code) {
        //     wx.hideLoading();
        //     wx.showModal({ content: '请填写动态码' });
        //     return;
        // }
         if (self.data.submit.mobile_code) {
        const _this = this;
        const param = {
            code: self.data.submit.mobile_code,
            name,
            sex,
            mobile: self.data.submit.phone,
        };
        wx.login({
            success: (res) => {
                if (res.errMsg == 'login:ok') {
                    wx.getUserInfo({
                        success(userResult) {
                            const appid = getIn(getExtConfig(), ['extAppid']);
                            global.actionDispatcher.execute(apiGetWxOpenId, {
                                wx_code: res.code,
                                appid,
                            }, (f, fs) => {
                                if (f === SUCCESS) {
                                    param.openId = fs.data.openid;
                                    param.head_photo = getIn(userResult, ['userInfo', 'avatarUrl']);
                                    global.actionDispatcher.execute(apiBandMobileRegister, param, (f, fs) => {
                                        if (f === SUCCESS) {
                                                wx.hideLoading();
                                                wx.showToast({
                                                    title: '注册成功',
                                                    icon: 'none',
                                                    duration: 1500,
                                                });

                                                const url = '/pages/index/index';
                                                wx.reLaunch({ url });
                                            } else if (f === FAIL) {
                                                wx.hideLoading();
                                                wx.showToast({ title: fs.msg, icon: 'none', duration: 1500 });
                                            }
                                    });
                                } else if (f === FAIL) {
                                    wx.hideLoading();
                                    wx.showToast({ title: '获取openId失败', icon: 'none', duration: 1500 });
                                }
                            });
                        },

                        fail(userError) {

                        },
                    });
                }
            },
            fail: (res) => {
                wx.hideLoading();
                wx.showToast({ title: '授权失败', icon: 'none', duration: 1500 });
            },
        });
        } else {
            wx.hideLoading();
            wx.showToast({
                title: '请填写手机验证码',
                icon: 'none',
                duration: 1500,
            });
        }
    },
});
